package com.auxgroup.smarthome.inner.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auxgroup.bridge.app.inner.vo.FamilyCenterDeviceVo;
import com.auxgroup.bridge.app.inner.vo.FamilyShareListVo;
import com.auxgroup.bridge.app.inner.vo.ShareResultVo;
import com.auxgroup.bridge.app.inner.vo.ShareUserListVo;
import com.auxgroup.bridge.app.inner.vo.SubShareUserVo;
import com.auxgroup.smarthome.constant.cache.CachedConsant;
import com.auxgroup.smarthome.enterprise.service.DeviceManageService;
import com.auxgroup.smarthome.enterpriseapi.requestbody.BindAndUnbindBody;
import com.auxgroup.smarthome.enterpriseapi.responsebody.DeviceMessage;
import com.auxgroup.smarthome.enums.DeviceSourceEnum;
import com.auxgroup.smarthome.inner.entity.AppUserEntity;
import com.auxgroup.smarthome.inner.entity.DeviceInfoEntity;
import com.auxgroup.smarthome.inner.entity.UserDeviceEntity;
import com.auxgroup.smarthome.inner.repo.AppUserEntityRepo;
import com.auxgroup.smarthome.inner.repo.DeviceInfoEntityRepo;
import com.auxgroup.smarthome.inner.repo.UserDeviceEntityRepo;
import com.auxgroup.smarthome.inner.util.DeviceHelper;
import com.auxgroup.smarthome.inner.vo.DeviceShareRelieveVo;
import com.auxgroup.smarthome.openapi.OpenApi;
import com.auxgroup.smarthome.openapi.requestbody.BindDidDeviceInfo;
import com.auxgroup.smarthome.openapi.requestbody.UnbindDeviceBody;
import com.auxgroup.smarthome.openapi.responsebody.BindAndUnbindStatus;
import com.auxgroup.smarthome.redis.config.ObjectRedis;
import com.auxgroup.smarthome.syscode.AppCode;
import com.auxgroup.smarthome.tree.TreeNode;
import com.auxgroup.smarthome.tree.TreeNodeBuilder;
import com.auxgroup.smarthome.utils.EncryptionUtils;
import com.auxgroup.smarthome.utils.NewDateUtils;
import com.auxgroup.smarthome.utils.common.LOG;
import com.auxgroup.smarthome.web.ApiResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

/**
 * 设备分享功能
 *
 * @Author: laiqiuhua.
 * @Date: 2017/7/28 10:03.
 */
@Service
@Transactional(readOnly = true)
public class DeviceShareInnerService {
    @Autowired
    private UserDeviceEntityRepo userDeviceEntityRepo;
    @Autowired
    private DeviceInfoEntityRepo deviceInfoEntityRepo;
    @Autowired
    private AppUserEntityRepo appUserEntityRepo;
    @Autowired
    private DeviceManageService deviceManageService;
    @Autowired
    private ObjectRedis objectRedis;

    private final String QR_PREFIX = "QR_AUX:"; // 二维码前缀
    private final String QR_SPLIT = "#"; // 二维码分隔符

    /**
     * 创建二维码分享
     *
     * @param uid
     * @param deviceIds
     * @param userTag
     * @return
     */
    public ApiResponse<ShareResultVo> createShare(String uid, String deviceIds, Integer userTag) {

        ApiResponse apiResponse = validateShare(uid, deviceIds);

        if (apiResponse.getCode() != AppCode.SC_OK.getCode()) {
            return apiResponse;
        }
        long curTimestamp = NewDateUtils.getCurrentEpochSecond();

        /**
         * 分享二维码内容生成：内容格式：QR_AUX:#设备id#分享者uid#分享类型#当前时间戳#随机4位数
         */
        StringBuilder sb = new StringBuilder();
        sb.append(QR_PREFIX)
                .append(deviceIds)
                .append(QR_SPLIT).append(uid)
                .append(QR_SPLIT).append(userTag)
                .append(QR_SPLIT).append(curTimestamp)
                .append(QR_SPLIT).append(ThreadLocalRandom.current().nextInt(10000));

        String qrContent = EncryptionUtils.base64Encode(sb.toString());

        return ApiResponse.ok(new ShareResultVo(qrContent));
    }

    /**
     * 分享校验
     *
     * @param uid
     * @param deviceIds
     * @return
     */
    private ApiResponse validateShare(String uid, String deviceIds) {
        List<String> deviceList = Arrays.asList(deviceIds.split(","));
        StringBuilder msg = new StringBuilder();
        StringBuilder relateMsg = new StringBuilder();
        // 好友不能分享设备提示
        StringBuilder frendShareMsg = new StringBuilder();
        deviceList.stream().forEach(deviceId -> {
            DeviceInfoEntity deviceInfoEntity = deviceInfoEntityRepo.findOne(deviceId);
            UserDeviceEntity userDeviceEntity = userDeviceEntityRepo.findByUidAndDeviceIdAndTrashFalse(uid, deviceId);
            if (null == deviceInfoEntity) {
                msg.append(deviceId).append(",");
            }
            if (null == userDeviceEntity) {
                relateMsg.append(deviceId).append(",");
            } else {
                if (userDeviceEntity.getUserTag() == 2) {
                    frendShareMsg.append(deviceId).append(",");
                }
            }
        });
        //  校验设备是否存在
        if (msg.length() > 0) {
            msg.setLength(msg.length() - 1);
            return ApiResponse.prompt(AppCode.DEVICE_NOT_EXIST.getCode(), String.format(AppCode.DEVICE_NOT_EXIST.getMsg(), msg.toString()));
        }

        if (relateMsg.length() > 0) {
            relateMsg.setLength(relateMsg.length() - 1);
            return ApiResponse.prompt(AppCode.USER_RELATION_DEVICE_NOT_EXIST.getCode(), String.format(AppCode.USER_RELATION_DEVICE_NOT_EXIST.getMsg(), relateMsg.toString()));
        }

        // 批量分享包含好友权限设备，不能进行分享
        if (frendShareMsg.length() > 0) {
            frendShareMsg.setLength(frendShareMsg.length() - 1);
            return ApiResponse.prompt(AppCode.FRIEND_CNANNOT_SHARE.getCode(), String.format(AppCode.FRIEND_CNANNOT_SHARE.getMsg(), frendShareMsg.toString()));
        }

        return ApiResponse.prompt(AppCode.SC_OK);
    }

    /**
     * 获取分享者列表
     *
     * @param shareUid
     * @return
     */
    public ApiResponse<List<ShareUserListVo>> getSharing(String shareUid, String deviceId) {
        AppUserEntity appUserEntity = appUserEntityRepo.findByUid(shareUid);
        if (appUserEntity == null) {
            ApiResponse.prompt(AppCode.ACCOUNT_IS_NOT_EXISTS);
        }
        List<ShareUserListVo> list = null;
        if (StringUtils.isNotEmpty(deviceId)) {
            list = userDeviceEntityRepo.findByShareUserIdAndDeviceId(shareUid, deviceId);
        } else {
            list = userDeviceEntityRepo.findByShareUserId(shareUid);
        }
        return ApiResponse.ok(list);
    }


    public ApiResponse<List<SubShareUserVo>> getSubShareUserList(String shareUid) {
        AppUserEntity appUserEntity = appUserEntityRepo.findByUid(shareUid);
        if (appUserEntity == null) {
            ApiResponse.prompt(AppCode.ACCOUNT_IS_NOT_EXISTS);
        }
        List<SubShareUserVo> list = userDeviceEntityRepo.findSubuserByShareUid(shareUid);

        return ApiResponse.ok(list);
    }

    /**
     * 扫描分享二维码事件
     *
     * @param uid
     * @param qrContent
     * @return
     */
    @Transactional(readOnly = false)
    public ApiResponse scanSharing(String appid, String token, String uid, String qrContent) {
        String decodeContent = EncryptionUtils.base64Decode(qrContent);
        if (!decodeContent.startsWith(QR_PREFIX)) {
            ApiResponse.prompt(AppCode.INVALID_QRCODE);
        }
        String parseQRStr = decodeContent.substring(QR_PREFIX.length(), decodeContent.length());
        String[] qRStrs = parseQRStr.split(QR_SPLIT);
        if (qRStrs.length != 5) {
            return ApiResponse.prompt(AppCode.INVALID_QRCODE);
        }
//        String deviceIds = qRStrs[0];
        String shareUid = qRStrs[1];
//        Integer userTag = Integer.valueOf(qRStrs[2]);
        long curTimestamp = Long.valueOf(qRStrs[3]);

        // 如果二维码超过15分钟，则过期了
        if (NewDateUtils.getCurrentInstant().minus(15, ChronoUnit.MINUTES).getEpochSecond() > curTimestamp) {
            return ApiResponse.prompt(AppCode.QRCODE_EXPIRED);
        }

        if (shareUid.equals(uid)) {
            return ApiResponse.prompt(AppCode.CANNOT_SHARE_SELF);
        }

        String QrBatch = UUID.randomUUID().toString();

        ApiResponse apiResponse = shareDevice(appid, token, uid, qRStrs, QrBatch);

        return apiResponse;
    }

    /**
     * 分享设备
     *
     * @param appid
     * @param token
     * @param uid
     * @param qRStrs
     * @return
     */
    private ApiResponse shareDevice(String appid, String token, String uid, String[] qRStrs, String qrBatch) {
        LOG.info(this, "----------------------开始分享设备------------------------");
        String deviceIds = qRStrs[0];
        String shareUid = qRStrs[1];
        Integer userTag = Integer.valueOf(qRStrs[2]);

        List<String> deviceList = Arrays.asList(deviceIds.split(","));
        StringBuilder msg = new StringBuilder();
        StringBuilder shareExpired = new StringBuilder();
        List<DeviceInfoEntity> deviceInfoEntities = new ArrayList<>();
        deviceList.stream().forEach(deviceId -> {
            DeviceInfoEntity deviceInfoEntity = deviceInfoEntityRepo.findByDeviceIdAndTrashFalse(deviceId);
            UserDeviceEntity owner = userDeviceEntityRepo.findByUidAndDeviceIdAndTrashFalse(shareUid, deviceId);
            if (null == deviceInfoEntity) {
                msg.append(deviceId).append(",");
            } else {
                deviceInfoEntities.add(deviceInfoEntity);
            }
            if (null == owner) {
                shareExpired.append(deviceId).append(",");
            }
        });
        if (msg.length() > 0) {
            msg.setLength(msg.length() - 1);
            ApiResponse apiResponse = ApiResponse.prompt(AppCode.DEVICE_NOT_EXIST.getCode(), String.format(AppCode.DEVICE_NOT_EXIST.getMsg(), msg.toString()));
            LOG.error(this, "分享失败："+JSON.toJSONString(apiResponse));
            return apiResponse;
        }

        if (shareExpired.length() > 0) {
            msg.setLength(shareExpired.length() - 1);
            ApiResponse apiResponse = ApiResponse.prompt(AppCode.DEVICE_SHARE_EXPIRED.getCode() + "", shareExpired.toString() + "分享设备已失效");
            LOG.error(this, "分享失败："+JSON.toJSONString(apiResponse));
            return apiResponse;
        }

        // 记录分享失败的uid
        List<String> failedUid = new ArrayList<>();
        List<String> bindFailDid = new ArrayList<>();
        LOG.info(this, "绑定分享设备的个数："+deviceInfoEntities.size());
        for(DeviceInfoEntity deviceInfoEntity: deviceInfoEntities) {

            // 机智云设备需要走PASS平台
            if (deviceInfoEntity.getSource() == 1) {
                ApiResponse<DeviceMessage> apiResponse = deviceManageService.getDeviceInfo(deviceInfoEntity.getProductKey(), deviceInfoEntity.getMac());
                if(apiResponse.getCode() == AppCode.SC_OK.getCode()) {
                    DeviceMessage deviceMessage = apiResponse.getData();
                    deviceInfoEntity.bindDidAndPasscode(deviceMessage.getDid(), deviceMessage.getPasscode());
                }

                BindDidDeviceInfo bindDidDeviceInfo = new BindDidDeviceInfo(deviceInfoEntity.getDid(), deviceInfoEntity.getPassword());
                LOG.info(this, "----------------------开始调用Openapi绑定设备------------------------");
                BindAndUnbindStatus result = OpenApi.bindDid(appid, token, bindDidDeviceInfo);
                LOG.info(this, "分享绑定==》调用PASS-Openapi-绑定设备："+JSONObject.toJSONString(result));

                if (StringUtils.isNotEmpty(result.getError_code()) || result.judgeFailed(deviceInfoEntity.getDid())) {
                    bindFailDid.add(bindDidDeviceInfo.getDid());
                    continue;
                }

            }

            // 分享后更新设备passcode
            deviceInfoEntityRepo.save(deviceInfoEntities);

            AppUserEntity appUserEntity = appUserEntityRepo.findOne(uid);

            // 把已经绑定的设备置为删除
            UserDeviceEntity bindedUser = userDeviceEntityRepo.findByDeviceIdAndUidAndTrashFalse(deviceInfoEntity.getDeviceId(), uid);
            if (null == bindedUser) {
                UserDeviceEntity userDeviceEntity = new UserDeviceEntity();
                userDeviceEntity.setQrBatch(qrBatch);
                userDeviceEntity.setDevAlias(deviceInfoEntity.getAlias());
                userDeviceEntity.buildDeviceShare(userTag, shareUid, uid, deviceInfoEntity.getDeviceId(), appUserEntity.getRealName(), appUserEntity.getPhone(), deviceInfoEntity.getMac(), deviceInfoEntity.getDid());
                userDeviceEntityRepo.save(userDeviceEntity);
                if (userDeviceEntity.getUserTag() == 2) {
                    // 好友分享缓存分享数据，8小时自动解绑
                    String key = CachedConsant.DEVICE_SHARE_CACHED_PREFIX + deviceInfoEntity.getDeviceId() + "/" + uid;
                    objectRedis.add(key, new DeviceShareRelieveVo(userDeviceEntity).buildAppToken(appid, token));
                }
            } else {
                failedUid.add(bindedUser.getUid());
            }
        }
        LOG.info(this, "绑定设备结束");

        // PASS 绑定失败提示信息
        if(bindFailDid.size() > 0) {
            LOG.info(this, "绑定失败did:"+Arrays.toString(bindFailDid.toArray()));
            ApiResponse apiResponse = ApiResponse.prompt(AppCode.DEVICE_BIND_FAIL.getCode(), "绑定失败did:"+Arrays.toString(bindFailDid.toArray()));
            return apiResponse;
        }

        if (failedUid.size() > 0) {
            LOG.info(this, "绑定失败did:"+String.format(AppCode.CANNOT_REPEAT_SHARE.getMsg(), Arrays.toString(failedUid.toArray())));
            ApiResponse apiResponse = ApiResponse.prompt(AppCode.CANNOT_REPEAT_SHARE.getCode(), String.format(AppCode.CANNOT_REPEAT_SHARE.getMsg(), Arrays.toString(failedUid.toArray())));
            return apiResponse;
        }
        return ApiResponse.prompt(AppCode.SC_OK);
    }

    /**
     * 清除设备分享缓存
     * @param deviceId
     * @param uid
     */
    private void clearShareRedisByDeviceIdAndUid(String deviceId, String uid) {
        // 删除分享数据缓存
        String key = CachedConsant.DEVICE_SHARE_CACHED_PREFIX + deviceId+ "/" + uid;
        objectRedis.delete(key);
    }

    /**
     * 解除分享
     *
     * @param appid
     * @param token
     * @param shareId
     * @return
     */
    @Transactional(readOnly = false)
    public ApiResponse relieveShare(String appid, String token, String shareId) {
        LOG.info(this, "----------------------开始解除分享设备------------------------");
        UserDeviceEntity deviceShareEntity = userDeviceEntityRepo.findByIdAndTrashFalse(shareId);
        if (null == deviceShareEntity) {
            return ApiResponse.prompt(AppCode.SHARE_NOT_EXISTS);
        }

        //----------- 解绑分享子用户设备------------//
        unbindSubuserDevice(appid, deviceShareEntity);

        deviceShareEntity.setTrash(true);

        DeviceInfoEntity deviceInfoEntity = deviceInfoEntityRepo.findByDeviceIdAndTrashFalse(deviceShareEntity.getDeviceId());
        if (null == deviceInfoEntity) {
            return ApiResponse.prompt(AppCode.DEVICE_NOT_EXIST);
        }
        // 解绑机智云设备
        ApiResponse apiResponse = unbindGizwitsDevice(appid, deviceShareEntity.getUid(), deviceInfoEntity);
        if (!apiResponse.isNotErrorCode()) {
            return apiResponse;
        }
        userDeviceEntityRepo.save(deviceShareEntity);

        // 删除分享数据缓存
        clearShareRedisByDeviceIdAndUid(deviceShareEntity.getDeviceId(), deviceShareEntity.getUid());

        return ApiResponse.prompt(AppCode.SC_OK);
    }

    private ApiResponse unbindGizwitsDevice(String appid, String uid, DeviceInfoEntity deviceInfoEntity) {
        if (deviceInfoEntity.getSource() == DeviceSourceEnum.GIZWITS.getSource()) {
            BindAndUnbindBody unbindDeviceBody = new BindAndUnbindBody();
            unbindDeviceBody.setAppid(appid);
            unbindDeviceBody.setUid(uid);
            unbindDeviceBody.setDids(new String[]{deviceInfoEntity.getDid()});
            LOG.info(DeviceHelper.class, "开始Enterpriseapi调用-解绑分享设备：参数：" + JSONObject.toJSONString(unbindDeviceBody));
            ApiResponse<com.auxgroup.smarthome.enterpriseapi.responsebody.BindAndUnbindStatus> bindAndUnbindStatus = deviceManageService.unbindDevices(deviceInfoEntity.getProductKey(), unbindDeviceBody);
            LOG.info(DeviceHelper.class, "结束Enterpriseapi调用" + JSONObject.toJSONString(bindAndUnbindStatus));
            if (!bindAndUnbindStatus.isNotErrorCode()) {
                return ApiResponse.prompt(AppCode.DEVICE_UNBIND_FAIL);
            }
        }
        return ApiResponse.ok();
    }

    /**
     * 解绑家人分享下的子用户
     * @param appid
     * @param deviceShareEntity
     */
    private void unbindSubuserDevice(String appid, UserDeviceEntity deviceShareEntity) {
        DeviceHelper.unbindSubuserDevice(userDeviceEntityRepo, deviceInfoEntityRepo, objectRedis, deviceManageService, appid, deviceShareEntity);
    }

    public List<TreeNode> buildUserDeviceTreeNode(String deviceId) {
        return TreeNodeBuilder.getInstance().buildListToTree(getAllUserDeviceNode(deviceId));
    }

    public List<TreeNode> getAllUserDeviceNode(String deviceId) {
        List<UserDeviceEntity> userDeviceEntities = userDeviceEntityRepo.findByDeviceIdAndTrashFalse(deviceId);
        List<TreeNode> treeNodes = userDeviceEntities.stream().map(x-> {
            TreeNode treeNode = new TreeNode(StringUtils.isEmpty(x.getShareUid())?"root":x.getShareUid(), x.getUid(), x);
            return treeNode;
        }).collect(Collectors.toList());
        return treeNodes;
    }

    /**
     * 获取家庭中心家人分享列表
     *
     * @param shareUid
     * @return
     */
    public List<FamilyShareListVo> getFamilySharing(String shareUid) {
        String querySql = "SELECT '' AS qr_batch,  0 AS expired_at, stat.uid, stat.share_total , 1 AS user_tag, aui.real_name AS username  FROM ( SELECT ud.uid, count(ud.id) share_total  FROM user_device ud WHERE ud.is_trash = 0 AND ud.share_uid = ?  AND ud.user_tag = 1 GROUP BY ud.uid ) stat LEFT JOIN app_user_info aui ON aui.uid = stat.uid";

        List<FamilyShareListVo> resultList = userDeviceEntityRepo.findBySql(querySql, Arrays.asList(shareUid), FamilyShareListVo.class);

        return resultList;
    }

    /**
     * 获取家庭中心好友分享列表
     *
     * @param shareUid
     * @return
     */
    public List<FamilyShareListVo> getFriendSharing(String shareUid) {
        StringBuffer querySql = new StringBuffer();
        querySql.append("SELECT DISTINCT stat.qr_batch, stat.uid, stat.share_total , ud1.username, ud1.user_tag , ud1.expired_at  FROM ")
                .append(" (SELECT ud.qr_batch, ud.uid, count(ud.id) share_total FROM user_device ud WHERE ud.user_tag = 2 AND ud.is_trash = 0 GROUP BY ud.qr_batch, ud.uid) stat ")
                .append("LEFT JOIN user_device ud1 ON stat.qr_batch = ud1.qr_batch WHERE ud1.share_uid =? ");
        List<FamilyShareListVo> resultList = userDeviceEntityRepo.findBySql(querySql.toString(), Arrays.asList(shareUid), FamilyShareListVo.class);

        return resultList;
    }

    /**
     * 解除好友到期分享
     *
     * @param appid
     * @param token
     * @param uid
     * @param deviceId
     * @return
     */
    @Transactional(readOnly = false)
    public ApiResponse relieveFriendShare(String appid, String token, String uid, String deviceId) {
        UserDeviceEntity deviceShareEntity = userDeviceEntityRepo.findByUidAndDeviceIdAndUserTagAndTrashFalse(uid, deviceId, 2);
        if (null == deviceShareEntity) {
            return ApiResponse.prompt(AppCode.SHARE_NOT_EXISTS);
        }

        DeviceInfoEntity deviceInfoEntity = deviceInfoEntityRepo.findByDeviceIdAndTrashFalse(deviceId);
        if (null == deviceInfoEntity) {
            return ApiResponse.prompt(AppCode.DEVICE_NOT_EXIST);
        }
        // 解绑机智云设备
        ApiResponse apiResponse = unbindGizwitsDevice(appid, deviceShareEntity.getUid(), deviceInfoEntity);
        if (!apiResponse.isNotErrorCode()) {
            return apiResponse;
        }
        deviceShareEntity.setTrash(true);
        userDeviceEntityRepo.save(deviceShareEntity);
        // 删除分享数据缓存
        clearShareRedisByDeviceIdAndUid(deviceShareEntity.getDeviceId(), deviceShareEntity.getUid());
        StringBuilder sb = new StringBuilder();
        sb.append("用户：").append(deviceShareEntity.getUid()).append("解除").append(deviceShareEntity.getDeviceId()).append("设备分享成功");
        LOG.info(this, sb.toString());
        return ApiResponse.ok(sb.toString());
    }

    /**
     * 获取当前用户分享给子用户的设备列表，获取家人设备列表batchNo可不填
     *
     * @param pUid
     * @param uid
     * @param batchNo 批次号，好友分享会生成一个批次号
     * @return
     */
    public List<FamilyCenterDeviceVo> getUserShareDeviceList(String pUid, String uid, int userTag, String batchNo) {
        List<UserDeviceEntity> userDeviceEntities = new ArrayList<>();
        if (userTag == 1) {
            userDeviceEntities = userDeviceEntityRepo.findByShareUidAndUidAndUserTagAndTrashFalse(pUid, uid, userTag);
        } else if (userTag == 2) {
            userDeviceEntities = userDeviceEntityRepo.findByShareUidAndUidAndUserTagAndQrBatchAndTrashFalse(pUid, uid, userTag, batchNo);
        }
        List<FamilyCenterDeviceVo> familyCenterDeviceVos = userDeviceEntities.stream().map(x -> {
            FamilyCenterDeviceVo familyCenterDeviceVo = FamilyCenterDeviceVo.of(x.getDeviceId(), x.getDevAlias(), x.getUsername(), x.getUid(), x.getQrBatch(), x.getUserTag());
            return familyCenterDeviceVo;
        }).collect(Collectors.toList());
        return familyCenterDeviceVos;
    }

    /**
     * 解除当前用户分享给子用户的设备，解除家人分享batchNo可不填
     *
     * @param pUid
     * @param uid
     * @param batchNo  好友分享批次号
     * @param deviceId
     * @return
     */
    @Transactional
    public ApiResponse relieveUserSharingByOwner(String appid, String token, String pUid, String uid, int userTag, String batchNo, String deviceId) {
        List<UserDeviceEntity> userDeviceEntities = new ArrayList<>();
        if (userTag == 1) {
            if (StringUtils.isBlank(deviceId)) {
                userDeviceEntities = userDeviceEntityRepo.findByShareUidAndUidAndUserTagAndTrashFalse(pUid, uid, userTag);
            } else {
                userDeviceEntities = userDeviceEntityRepo.findByShareUidAndUidAndDeviceIdAndTrashFalse(pUid, uid, deviceId);
            }
        } else if (userTag == 2) {
            if(StringUtils.isBlank(batchNo)) {
                return ApiResponse.prompt(AppCode.SHARE_FRIEND_DEVICE_BATCH_MUST_NOT_NULL);
            }
            if (StringUtils.isBlank(deviceId)) {
                userDeviceEntities = userDeviceEntityRepo.findByShareUidAndUidAndUserTagAndQrBatchAndTrashFalse(pUid, uid, userTag, batchNo);
            } else {
                userDeviceEntities = userDeviceEntityRepo.findByShareUidAndUidAndDeviceIdAndTrashFalse(pUid, uid, deviceId);
            }
        }
        userDeviceEntities = userDeviceEntities.stream().map(x-> {
            //----------- 解绑分享子用户设备------------//
            unbindSubuserDevice(appid, x);

            UnbindDeviceBody unbindDeviceBody = new UnbindDeviceBody();
            unbindDeviceBody.buildDidList(x.getDid());
            BindAndUnbindStatus bindAndUnbindStatus = OpenApi.unbindByDids(appid, token, unbindDeviceBody);

            if (StringUtils.isNotEmpty(bindAndUnbindStatus.getError_code()) && bindAndUnbindStatus.judgeFailed(x.getDid())) {
                LOG.error(this, JSON.toJSONString(bindAndUnbindStatus));
            }

            // 删除分享数据缓存
            clearShareRedisByDeviceIdAndUid(x.getDeviceId(), x.getUid());

            x.setTrash(true);
            return x;
        }).collect(Collectors.toList());
        userDeviceEntityRepo.save(userDeviceEntities);
        return ApiResponse.ok();
    }


}
